package com.zhq.blog.manage.domain.controller.money;

import javax.validation.Valid;

import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zhq.blog.core.domain.money.BusinessMan;
import com.zhq.blog.manage.domain.controller.BaseController;
import com.zhq.blog.manage.domain.controller.BossModel;

@Controller
@Scope("prototype")
@RequestMapping("/admin/money/businessMan/*")
public class BusinessManController extends BaseController {
	
	@RequestMapping()
    public BossModel index(@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
		return createModel("admin/money/businessMan/list").add("businessManPage",context.getBusinessManRepository().findAll(pageable)).add("viewState", "");
	}
	
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){
		return createModel("admin/money/businessMan/info").add("businessMan",context.getBusinessManRepository().findOne(id));
	}
	
	@RequestMapping(value="add")
	public BossModel add(){
		return createPrizeModel(new BusinessMan());
	}
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	public BossModel save(@Valid final BusinessMan businessMan, final BindingResult bindingResult, final ModelMap model, RedirectAttributes redirectBusinessMan,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		if (bindingResult.hasErrors()) {
			return createModel("admin/money/businessMan/info");
		}
		context.getBusinessManRepository().save(businessMan);
		String message = businessMan.getSucessFlashMessage();
		redirectBusinessMan.addFlashAttribute("message", message);
		return createModel("redirect:/admin/money/businessMan/index");
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
		context.getBusinessManRepository().delete(id);
		return createModel("admin/money/businessMan/businessMan_table").add("businessManPage",context.getBusinessManRepository().findAll(pageable));
	}
	
	private BossModel createPrizeModel(BusinessMan businessMan){
		BossModel modelAndView = createModel("admin/money/businessMan/info");
		if(businessMan != null)
			modelAndView.add("businessMan",businessMan);
		return modelAndView;
	}

}
